import React, { useEffect, useState } from 'react'
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { convertToRaw, ContentState, EditorState } from 'draft-js'
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';



export default function NewsEditor(props) {
    const [editorState, setEditorState] = useState('')
    useEffect(() => {
        // console.log(props.content);
        // 此时是html代码<p>xxx</p>
        const html = props.content;
        // 如果是添加功能的话,html为空
        if(html===undefined) return 
        const contentBlock = htmlToDraft(html);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const editor = EditorState.createWithContent(contentState);
            setEditorState(editor)
        }
    }, [props.content])

    
    return (
        <div>
            <Editor
                // 受控editorState,控制onEditorStateChange  
                editorState={editorState}
                onEditorStateChange={(editorState) => setEditorState(editorState)}
                // 整个盒子
                wrapperClassName="aaa"
                // 工具盒子
                toolbarClassName="bbb"
                // 内容盒子
                editorClassName="ccc"

                onBlur={() => {
                    props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
                }}
            />
        </div>
    )
}
